import React, { useEffect, useRef, useState } from 'react';
import {
  CloseCircleOutlined,
  CloseOutlined,
  PlusCircleOutlined,
  PlusOutlined,
} from '@ant-design/icons';
import type { InputRef } from 'antd';
import { Input, Tag, Tooltip } from 'antd';
import styles from './TabsTitle.module.less';
import classNames from 'classnames';
import uniqueId from 'lodash';
import { useTrackedEffect } from 'ahooks';

const TabsTitle: React.FC = () => {
  const [tags, setTags] = useState<string[]>([
    'Tab 1',
    'Tab 2',
    'Tab 3',
    'Tab 4',
    'Tab 5',
  ]);
  const [inputVisible, setInputVisible] = useState(false);
  const [inputValue, setInputValue] = useState('');
  const [editInputIndex, setEditInputIndex] = useState(-1);
  const [editInputValue, setEditInputValue] = useState('');
  const [activeTab, setActiveTab] = useState<string>('Tab 1'); // 当前激活的 Tab
  const inputRef = useRef<InputRef>(null);
  const editInputRef = useRef<InputRef>(null);

  const isMountedRef = useRef(true);

  useEffect(() => {
    isMountedRef.current = true;
    return () => {
      isMountedRef.current = false;
    };
  }, []);

  useEffect(() => {
    if (inputVisible && isMountedRef.current) {
      inputRef.current?.focus();
    }
  }, [inputVisible]);

  useEffect(() => {
    if (isMountedRef.current) {
      editInputRef.current?.focus();
    }
  }, [editInputValue]);

  useTrackedEffect(
    (changes, pre, cur) => {
      console.log(changes, pre, cur);
    },
    [activeTab],
  );

  const handleClose = (removedTag: string) => {
    setTags((prevTags) => {
      const newTags = prevTags.filter((tag) => tag !== removedTag);
      if (removedTag === activeTab && newTags.length > 0) {
        setActiveTab(newTags[0]); // 在更新 tags 之后再更新 activeTab
      }
      return newTags;
    });
  };

  const showInput = () => {
    setInputVisible(true);
  };

  const handleInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setInputValue(e.target.value);
  };

  const handleInputConfirm = () => {
    if (inputValue && !tags.includes(inputValue)) {
      setTags([...tags, inputValue]);
    }
    setInputVisible(false);
    setInputValue('');
  };

  const handleEditInputChange = (e: React.ChangeEvent<HTMLInputElement>) => {
    setEditInputValue(e.target.value);
  };

  const handleEditInputConfirm = () => {
    const newTags = [...tags];
    newTags[editInputIndex] = editInputValue;
    setTags(newTags);
    setEditInputIndex(-1);
    setEditInputValue('');
  };

  const handleTagClick = (tag: string) => {
    setActiveTab(tag); // 切换激活的 Tab
  };

  const tagPlusStyle: React.CSSProperties = {
    height: 22,
    borderStyle: 'dashed',
  };

  return (
    <div>
      <div
        className={classNames(styles.titleTabs, 'titleTabs flex items-center')}
      >
        {tags.map<React.ReactNode>((tag, index) => {
          if (editInputIndex === index) {
            return (
              <div
                key={uniqueId(tag)}
                className={classNames(
                  'flex justify-center items-center ml-10px mr-10px',
                )}
              >
                <Input
                  ref={editInputRef}
                  key={tag}
                  // size="small"
                  // style={tagInputStyle}
                  className=""
                  value={editInputValue}
                  onChange={handleEditInputChange}
                  onBlur={handleEditInputConfirm}
                  onPressEnter={handleEditInputConfirm}
                />
              </div>
            );
          }
          const isLongTag = tag.length > 20;
          const tagElem = (
            <div
              key={uniqueId(tag)}
              className={classNames(
                styles.tabs,
                tag === activeTab ? styles.active : '',
                ' px-40px cursor-pointer py-6px relative',
              )}
            >
              <div
                style={{
                  userSelect: 'none',
                  color: tag === activeTab ? 'black' : '',
                }}
                onClick={() => handleTagClick(tag)}
              >
                <span
                  onDoubleClick={(e) => {
                    setEditInputIndex(index);
                    setEditInputValue(tag);
                    e.preventDefault();
                  }}
                >
                  {isLongTag ? `${tag.slice(0, 20)}...` : tag}
                </span>
                <CloseCircleOutlined
                  className={classNames(styles.close, 'absolute top-0 right-0')}
                  onClick={() => handleClose(tag)}
                />
              </div>
            </div>
          );
          return isLongTag ? (
            <Tooltip title={tag} key={tag}>
              {tagElem}
            </Tooltip>
          ) : (
            tagElem
          );
        })}
        {inputVisible ? (
          <Input
            ref={inputRef}
            type="text"
            value={inputValue}
            onChange={handleInputChange}
            onBlur={handleInputConfirm}
            onPressEnter={handleInputConfirm}
          />
        ) : (
          // <Tag style={tagPlusStyle} icon={<PlusOutlined />} onClick={showInput}>
          //   New Tab
          // </Tag>
          <PlusOutlined
            onClick={showInput}
            className="cursor-pointer ml-10px"
            style={{ color: '#1890ff' }}
          />
        )}
      </div>

      <div style={{ marginTop: 16 }}>
        <h3>盛放对应标签的内容: {activeTab}</h3>
      </div>
    </div>
  );
};

export default TabsTitle;
